package Main;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class SelectCarGoods {
	String url = "jdbc:mysql://localhost:3306/goods";
    String userName = "root";
    String password = "kamisama";
    String driverName = "com.mysql.jdbc.Driver";
    String strSql1 = "select *from cars";
    Connection con1 = null;
	java.sql.PreparedStatement pstmt1 = null;
	ResultSet rs = null;
	String driverName1 = "com.mysql.jdbc.Driver";
    Scanner sc = new Scanner(System.in);
	public void SelectGooks(){
	    try {
	        Class.forName(driverName);// jdbc4.0 后无需使用这句进行驱动注册操作
	        con1 = (Connection) DriverManager.getConnection(url, userName, password); // 根据参数的插入数据
	        pstmt1 = con1.prepareStatement(strSql1);
	        rs = pstmt1.executeQuery(strSql1);
	        while (rs.next()) {
	            int id = rs.getInt("id");
	            String name = rs.getString("name");
	            String price = rs.getString("price");
	            int num = rs.getInt("num");
	            String description = rs.getString("description");
	            System.out.print("id=" + id + "  name="+name+" price="+price+"  num=" + num+"description="+description+"\n");
	        }
	    } catch (SQLException e) {
	        e.printStackTrace();
	    } catch (ClassNotFoundException e) {
	        e.printStackTrace();
	    } finally {/*下面资源释放，可以使用try..with..resources语法简化*/
	        if (rs != null) {
	            try {
	                rs.close();
	                rs.close();
	            } catch (SQLException e) {
	                e.printStackTrace();
	            }
	        }
	        if (pstmt1 != null) {
	            try {
	            	pstmt1.close();
	            	pstmt1 = null;
	            } catch (SQLException e) {
	                e.printStackTrace();
	            }
	        }
	        if (con1 != null)
	            try {
	                con1.close();
	                con1 = null;
	            } catch (SQLException e) {
	                e.printStackTrace();
	            } 
	    	}
	    }
}
